<?php
//1fcaa4861ac124ea8534414fd1f7da12
if($_REQUEST['key'] != md5(md5('odd-even-api'))){
	exit;
}
/* 接口参数限制 */
$param = array(
	'http' => array('d.apiplus.net','z.apiplus.net',''),
	'token' => 'e981d76525ee8b19',
);

$http = $_REQUEST['http'] ? $param['http'][$_REQUEST['http']] : $param['http'][0];
$date = $_REQUEST['date'] ? ($_REQUEST['date'] == 'extend' ? '&extend=true' : '&date='.$_REQUEST['date']) : '';
$format =  $_REQUEST['format'] ? $_REQUEST['format'] : 'json';
$limit = $_REQUEST['limit'] ? $_REQUEST['limit'] : 5;

$mode = $_REQUEST['mode'] ? $_REQUEST['mode'] : false;
if($mode){
	$url = 'http://'.$http.'/'.$param['token'].'/cqssc-'.$limit.'.'.$format;
}else{
	$url = 'http://'.$http.'/newly.do?token='.$param['token'].'&code=cqssc&rows='.$limit.'&format='.$format.$date;
}

/*定时执行功能.带是否循环*/
ignore_user_abort();//关掉浏览器，PHP脚本也可以继续执行.
set_time_limit(0);// 通过set_time_limit(0)可以让程序无限制的执行下去
$db = include('data/config/db.php');
//执行查询与更新
$db['dbhost'] = $db['DB_HOST'] == 'localhost' ? '127.0.0.1' : $db['DB_HOST'];
$db['dbport'] = $db['DB_PORT'];
$db['dbname'] = $db['DB_NAME'];
$db['dbuser'] = $db['DB_USER'];
$db['dbpass'] = $db['DB_PWD'];
$db['dbtype'] = 'mysql';
$pdodb = new pdomysql($db);
$result = doGet($url);
$result = json_decode($result,true);
$data = $result['data'];
foreach($data as $val){
	$sql = 'SELECT id FROM ins_ssc_data WHERE `expect` = "'.$val['expect'].'"';
	$is_exist = $pdodb->getOne($sql);
	if($is_exist > 0){
		continue;
	}

	$pdodb->doInsert('ins_ssc_data',array(
		'expect' => $val['expect'],
		'opencode' => $val['opencode'],
		'opentime' => $val['opentime'],
		'opentimestamp' => $val['opentimestamp'],
		'lastno' => substr($val['opencode'],-1)
	));
}

echo '执行完毕';exit;
class pdomysql {
	protected $pdo;
	public $config = array();
	public $dbtype;
	public $dbhost;
	public $dbport;
	public $dbname;
	public $dbuser;
	public $dbpass;
	public $dbchar = 'utf8';
	public $prefix = 'it';
	public $dbline = true;
	public $err = false;
	static $recursionlist = array();
	static $total = 0;
	static $totaltime = 0;
	static $sqltime = array();

	public function __construct($config=''){
		if(!$this->config || empty($this->config)){
			$this->config = $config;
		}
		if(!$this->dbtype){
			$this->dbtype = $this->config['dbtype'];
		}
		if(!$this->dbhost){
			$this->dbhost = $this->config['dbhost'];
		}
		if(!$this->dbport){
			$this->dbport = $this->config['dbport'];
		}
		if(!$this->dbname){
			$this->dbname = $this->config['dbname'];
		}
		if(!$this->dbuser){
			$this->dbuser = $this->config['dbuser'];
		}
		if(!$this->dbpass){
			$this->dbpass = $this->config['dbpass'];
		}
		if(!$this->dbchar){
			$this->dbchar = $this->config['dbchar'];
		}
		if(!$this->dbline){
			$this->dbline = $this->config['dbline'];
		}
		$this->prefix = $this->config['prefix'] ? $this->config['prefix'] : 'it';

		$link = $this->dbtype.':dbname='.$this->dbname.';host='.$this->dbhost.';port='.$this->dbport;
		try{
			//$this->pdo = new PDO($link,$this->dbuser,$this->dbpass,array(PDO::ATTR_PERSISTENT=>$this->dbline));
			$this->pdo = new PDO($link,$this->dbuser,$this->dbpass);
			$this->query('SET names '.$this->dbchar.';');
		}catch(PDOException $e){
			header("Content-type:text/html;charset=utf-8");
			echo '数据库连接出错: '.$link.$e->getMessage();
			exit;
		}
	}

	/*数据库关闭*/
    public function close(){
        $this->pdo = null;
    }
	
	//查询语句
	public function query($sql){
		if(!$sql) return false;
		if($this->err==true) return $sql;
        $res = $this->pdo->query($sql,PDO::FETCH_ASSOC);
        if($res){
			$res = $this->PDOStatementObjectToArray($res);
            return $res;
        }
    }
	
	//输出所有查询
	public function getAll($sql){
		if(!$sql) return false;
		$res = $this->query($sql);
        if($res){
            return $res;
        }
        return false;
    }

	public function getRow($sql){
		if(!$sql) return false;
		//if(strpos($sql,'LIMIT')===false){
		//	$sql .= ' LIMIT 0,1 ';
		//}
		$res = $this->query($sql);
		if ($res != false){
			$row = $res[0];
			if ($row != false){
				return $row;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}

    public function getOne($sql){
		if(!$sql) return false;
		//if(strpos($sql,'LIMIT')===false){
		//	$sql .= ' LIMIT 0,1 ';
		//}
		$res = $this->getRow($sql);
		if($res != false){
			foreach($res AS $v){
				return $v;
			}
		}else{
			return false;
		}
	}

	public function getCount($table,$field,$where=false){
		$where = $where ? ' WHERE '.$where :'';
		$sql = 'SELECT count('.$field.') AS cccc FROM '.$table.$where;
		return $this->getOne($sql);
	}

	function getField($table){
		if(!$table) return false;
		$sql = 'DESCRIBE '.$table;
		$res = $this->query($sql);
		if ($res != false){
			$arr = array();
			foreach($res AS $k=>$v){
				$arr[] = '`'.$v['Field'].'`';
			}
			return $arr;
		}else{
			return false;
		}
	}
	
	public function doExec($sql){
		$s = microtime(true);
		if(!$sql) return false;
		try{
			$id = $this->pdo->exec($sql);
		}catch(PDOException $e){
			echo 'Connection failed: '.$e->getMessage();
		}
		if(!$id && $this->err===true) $id = $sql;
		$e = round(microtime(true)-$s,6);
		self::$sqltime[]=$e.'*'.$sql;
		self::$totaltime += $e;
		self::$total++;
		return $id;
	}

	public function doInsert($table,$fields){
		if(!$table || !$fields || empty($fields)) return false;
		return $this->autoExecute($table,$fields);
	}

	public function doUpdate($table,$fields,$where=''){
		if(!$table || !$fields || empty($fields) || !$where) return false;
		return $this->autoExecute($table,$fields,'update',$where);
	}

	public function doDelete($table,$where=''){
		if(!$table) return false;
		if($where){
			$where = ' WHERE '.$where;
		}
		$sql ="DELETE FROM ".$table.$where;
		return $this->doExec($sql);
	}

	public function doInc($table,$fields,$where,$number=1){
		$number = intval($number);
		if($number>0){
			$sql = 'UPDATE `'.$table.'` SET `'.$fields.'`=`'.$fields.'`+'.$number.' WHERE '.$where;
		}elseif($number<0){
			$sql = 'UPDATE `'.$table.'` SET `'.$fields.'`=`'.$fields.'`'.$number.' WHERE '.$where;
		}else{
			return false;
		}
		return $this->query($sql);
	}
	
	/**
	 * 批量插入
	 * $fields 字段数组
	 * $data 待插入数据 array(
							array(值1,值2,值3,值4,值5),
							array(值1,值2,值3,值4,值5),
							array(值1,值2,值3,值4,值5),
						);
	 */
	public function batchInsert($table,$key,$data){
		$fn = $this->getField($table);
		if(!$fn || !$data || empty($data)) return false;
		$sql = '';
		foreach($fn AS $value){
			if(in_array(trim($value,'`'),$key) == true){
				$fields[] = $value;
			}
		}
		foreach($data AS $k=>$v){
			$values[] = '("'.implode('","',$v).'")';
		}
		$sql = 'INSERT INTO '.$table.' ('.implode(',',$fields).') VALUES '.implode(',',$values);
		return $this->doExec($sql);
	}

	public function autoExecute($table,$field,$mode='INSERT',$where='',$showsql=false){
		$fn = $this->getField($table);
		if(!$fn) return false;
		$sql = '';
		if ($mode == 'INSERT'){
			$field['intime'] = $field['intime'] ? $field['intime'] : time();
			$fields = $values = array();
			foreach($fn AS $value){
				if(array_key_exists(trim($value,'`'), $field) == true){
					$fields[] = $value;
					$values[] = "'".$field[trim($value,'`')]."'";
				}
			}
			if(!empty($fields)){
				$sql = 'INSERT INTO '.$table.' ('.implode(',',$fields).') VALUES ('.implode(',',$values).')';
			}
		}else{
			$sets = array();
			foreach($fn AS $value){
				if(array_key_exists(trim($value,'`'), $field) == true){
					$sets[] = $value."='".$field[trim($value,'`')]."'";
				}
			}
			if(!empty($sets)){
				$sql = 'UPDATE '.$table.' SET '.implode(',',$sets).' WHERE '.$where;
			}
		}
		if($showsql) return $sql;
		if($sql){
			$this->doExec($sql);
			if($mode=='INSERT'){return $this->insertId();}
			return true;
		}else{
			return false;
		}
    }

    public function insertId(){
		return $this->pdo->lastInsertId();
	}
	
	//格式化数组
	protected function PDOStatementObjectToArray($arr){
		$ret = array();
		if(empty($arr)) return false;
		foreach($arr AS $key =>$value){
			if(gettype($value) == 'array' || gettype($value) == 'object'){
				$ret[$key] = $this->PDOStatementObjectToArray($value);
			}else{
				$ret[$key] = $value;
			}
		}
		return $ret;
	}
}

function doGet($url,$data=false){
	if(is_array($data)){
		foreach($data AS $k=>$v){
			$grr[]=$k.'='.$v;
		}
		$txt = implode($grr,'&');
	}else{
		$txt = $data;
	}
	$target = $txt ? $url.'?'.$txt : $url;
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $target); // 要访问的地址
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
	curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
	//curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
	//curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
	curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
	curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
	$result = curl_exec($curl);
	curl_close($curl);
	return $result;
}